package cn.com.ry.framework.linklog.logging.log4j2;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class Log4j2LinkLogSystem {
    private static final Logger logger = LoggerFactory.getLogger(Log4j2LinkLogSystem.class);

    public static String OFF = "OFF";
    public static String FATAL = "FATAL";
    public static String ERROR = "ERROR";
    public static String WARN = "WARN";
    public static String INFO = "INFO";
    public static String DEBUG = "DEBUG";
    public static String TRACE = "TRACE";
    public static String ALL = "ALL";

    public static String ROOT = "ROOT";

    /**
     * 设置日志级别
     *
     * @param loggerName logger名称
     * @param level 日志级别
     */
    public static void setLevel(String loggerName, String level) {
        try {
            if (loggerName == null || loggerName.trim().equals("") || Log4j2LinkLogSystem.ROOT.equalsIgnoreCase(loggerName)) {
                loggerName = LogManager.ROOT_LOGGER_NAME;
            }
            LoggerConfig loggerConfig = LoggerContext.getContext(false).getConfiguration().getLoggers().get(loggerName);
            Level log4jLevel = convertLogLevel(level);
            if (log4jLevel != null) {
                loggerConfig.setLevel(log4jLevel);
            }
        } catch (Exception e) {
            logger.error("日志级别修改错误");
        }

    }


    public static Level convertLogLevel(String level) {
        if (level != null && !level.equals("")) {
            if (level.equalsIgnoreCase(Log4j2LinkLogSystem.ALL)) {
                return Level.ALL;
            } else if (level.equalsIgnoreCase(Log4j2LinkLogSystem.TRACE)) {
                return Level.TRACE;
            } else if (level.equalsIgnoreCase(Log4j2LinkLogSystem.DEBUG)) {
                return Level.DEBUG;
            } else if (level.equalsIgnoreCase(Log4j2LinkLogSystem.INFO)) {
                return Level.INFO;
            } else if (level.equalsIgnoreCase(Log4j2LinkLogSystem.DEBUG)) {
                return Level.DEBUG;
            } else if (level.equalsIgnoreCase(Log4j2LinkLogSystem.WARN)) {
                return Level.WARN;
            } else if (level.equalsIgnoreCase(Log4j2LinkLogSystem.ERROR)) {
                return Level.ERROR;
            } else if (level.equalsIgnoreCase(Log4j2LinkLogSystem.FATAL)) {
                return Level.FATAL;
            } else if (level.equalsIgnoreCase(Log4j2LinkLogSystem.OFF)) {
                return Level.OFF;
            }
        }
        return null;

    }
}
